//
//  MTChatSingleDetailViewController.swift
//  MT
//
//  Created by ooops on 2020/5/7.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import YPNavigationBarTransition

enum ChatItemTypeStruct {
    /// 备注
    case remark
    /// 查找聊天内容
    case chatContent
    /// 消息免打扰
    case unDisturb
    /// 置顶
    case roofTop
    /// 清除聊天内容
    case clearChat
    /// 投诉
    case report
}

public struct ChatItemStruct {
    var itemName: String
    var isShowArrow: Bool
    var isShowSwitch: Bool
    var type: ChatItemTypeStruct
    
    mutating func create(itemName: String, isShowArrow: Bool, isShowSwitch: Bool, type: ChatItemTypeStruct) -> ChatItemStruct {
        self.itemName = itemName
        self.isShowArrow = isShowArrow
        self.isShowSwitch = isShowSwitch
        self.type = type
        return self
    }
}

class MTChatSingleDetailViewController: BaseViewController {
    
    var user: JMSGUser!
    
    var conversation: JMSGConversation!
    
    let dataSource: [[ChatItemStruct]] = [
        [ChatItemStruct(itemName: "设置备注名", isShowArrow: true, isShowSwitch: false, type: .remark),
         ChatItemStruct(itemName: "查找聊天内容", isShowArrow: true, isShowSwitch: false, type: .chatContent)],
        [ChatItemStruct(itemName: "消息免打扰", isShowArrow: false, isShowSwitch: true, type: .unDisturb),
         ChatItemStruct(itemName: "置顶聊天", isShowArrow: false, isShowSwitch: true, type: .roofTop)],
        [ChatItemStruct(itemName: "清空聊天内容", isShowArrow: false, isShowSwitch: false, type: .clearChat)]]
    //,ChatItemStruct(itemName: "投诉", isShowArrow: true, isShowSwitch: false, type: .report)

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    

    lazy var tableView: UITableView = {
        let table = UITableView(frame: view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(MTChatSingleDetailCell.self, forCellReuseIdentifier: MTChatSingleDetailCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.sectionFooterHeight = 0
        table.sectionHeaderHeight = 0
        return table
    }()

}


extension MTChatSingleDetailViewController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTChatSingleDetailCell.reuseIdentity(), for: indexPath) as! MTChatSingleDetailCell
        cell.delegate = self
        cell.user = user
        cell.conversation = conversation
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTChatSingleDetailCell, forRowAt indexPath: IndexPath) {
        let data: ChatItemStruct = self.dataSource[indexPath.section][indexPath.row]
        
        cell.bindData(data: data)
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data: ChatItemStruct = self.dataSource[indexPath.section][indexPath.row]
        switch data.type {
        case .remark:
            let vc = MTEditFriendRemarkNameViewController()
            vc.user = user
            let nav = BaseNavController(rootViewController: vc)
            nav.modalPresentationStyle = .fullScreen
            nav.modalTransitionStyle = .crossDissolve
            self.navigationController?.present(nav, animated: true, completion: nil)
            break
        case .chatContent:
            let vc = FileManagerViewController()
            let conv = JMSGConversation.singleConversation(withUsername: user.username)
            vc.conversation  = conv
            navigationController?.pushViewController(vc, animated: true)
        case .clearChat:
            UIAlertController.rx.show(in: self, title: "提示", message: "是否清除聊天内容, 清除后将无法恢复", buttons: [.cancel("取消"), .default("确定")]).subscribe(onSuccess: {[weak self] index in
                guard let weakSelf = self else { return }
                if index == 1 {
                    let conv = JMSGConversation.singleConversation(withUsername: weakSelf.user.username)
                    conv?.deleteAllMessages()
                    NotificationCenter.default.post(name: Notification.Name(rawValue: kDeleteAllMessage), object: nil)
                    MBProgressHUD_JChat.show(text: "成功清空", view: weakSelf.view)
                }
            })
            .disposed(by: globalDisposedBag)
        case .report:
            break
        default:
            break
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTChatSingleDetailViewController: MTChatSingleDetailCellDelegate {
    
    func didOpenSwitch(sender: UISwitch, data: ChatItemStruct?) {
        guard let d = data else { return }
        switch d.type {
        case .unDisturb:
            if user.isNoDisturb != sender.isOn {
                MBProgressHUD_JChat.showMessage(message: "修改中", toView: view)
                user.setIsNoDisturb(sender.isOn, handler: { (result, error) in
                    MBProgressHUD_JChat.hide(forView: self.view, animated: true)
                    if error == nil {
                        MBProgressHUD_JChat.show(text: "修改成功", view: self.view)
                    } else {
                        MBProgressHUD_JChat.show(text: "修改失败", view: self.view)
                    }
                })
            }
            break
        case .roofTop:
            conversation.ex.isSticky = !conversation.ex.isSticky
            break
        default:
            break
        }
    }
    
}

extension MTChatSingleDetailViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
    
}
